//
//  CEIBarPlot.m
//  Balance
//
//  Created by Calvin Kuo on 12-05-31.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

/*
 Status: changed
 Last Merge Date: 05-30-2012
 Last Change Date: 
 Changes:
 Changes:
 1. new file
 */

#import "CEIBarPlot.h"
#import "CEIData.h"

@implementation CEIBarPlot

@synthesize country = _country;
@synthesize countryCEI = _countryCEI;
@synthesize allCEI = _allCEI;

- (id) init {
    self = [super init];
    if(self){
        _country = nil;
        _countryCEI = nil;
        _allCEI = nil;
        
    }
    return self;
}


- (id)initWithCountryNames:(NSArray *)countryNames andCurrentData:(NSDictionary *) currentData andAllCollectorsData:(NSDictionary *) allData
{
    self = [self init];
    if (self) 
    {
        _country = countryNames;
        _countryCEI = currentData;
        _allCEI = allData;
    }
    return self;
}

- (void)renderInLayer:(CPTGraphHostingView *)layerHostingView withTheme:(CPTTheme *)theme
{
    
    CGRect bounds = layerHostingView.bounds;
    
    // create and assign chart to the hosting view.
    graph = [[CPTXYGraph alloc] initWithFrame:bounds];
    layerHostingView.hostedGraph = graph;
    layerHostingView.backgroundColor = [UIColor colorWithWhite:0.7f alpha:1.0f]; 
    
    CPTGradient *plotAreaGradient = [CPTGradient gradientWithBeginningColor:[CPTColor colorWithGenericGray:0.9f]endingColor:[CPTColor colorWithGenericGray:0.6f]];
    plotAreaGradient.angle = -90.0;
    graph.plotAreaFrame.plotArea.fill = [CPTFill fillWithGradient:plotAreaGradient]; 
    
    [graph applyTheme:theme];
    
    graph.plotAreaFrame.masksToBorder = NO;
    
    graph.paddingLeft = 120.0;
	graph.paddingTop = 120.0;  //50.0
	graph.paddingRight = 90.0;
	graph.paddingBottom = 80.0;
    
    CPTMutableTextStyle *blackTextStyle = [[CPTMutableTextStyle alloc] init];
	//blackTextStyle.color = [CPTColor blackColor];
    blackTextStyle.color = [CPTColor colorWithComponentRed:0.2 green:0.2 blue:0.2 alpha:0.82]; //RGB:R51-G51-B51
	blackTextStyle.fontSize = 20.0;
    graph.titleTextStyle = blackTextStyle;
    graph.titleDisplacement = CGPointMake(0.0, 90.0); 
    graph.title = @"Collection Effectiveness Index By Country";
    

    
    // chang the chart layer orders so the axis line is on top of the bar in the chart.
    NSArray *chartLayers = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:CPTGraphLayerTypeAxisLines],  
                            [NSNumber numberWithInt:CPTGraphLayerTypePlots], 
                            [NSNumber numberWithInt:CPTGraphLayerTypeMajorGridLines], 
                            [NSNumber numberWithInt:CPTGraphLayerTypeMinorGridLines],
                            [NSNumber numberWithInt:CPTGraphLayerTypeAxisLabels], 
                            [NSNumber numberWithInt:CPTGraphLayerTypeAxisTitles], nil];
    
    graph.topDownLayerOrder = chartLayers;
    
	// Add plot space for horizontal bar charts
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;    
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(0) length:CPTDecimalFromInt(100)];
    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(0) length:CPTDecimalFromInt(5)];
    
    // Setting X-Axis
    CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
    CPTXYAxis *x = axisSet.xAxis;
    x.labelingPolicy = CPTAxisLabelingPolicyNone;
    x.title = @"Country";
    x.titleOffset = 30.0f;
    x.majorTickLineStyle = nil;
    x.minorTickLineStyle = nil;
    x.majorIntervalLength = CPTDecimalFromString(@"1.0");
    x.orthogonalCoordinateDecimal = CPTDecimalFromString(@"0");
    x.labelExclusionRanges = [NSArray arrayWithObjects:[CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(6) length:CPTDecimalFromInt(1)], nil];
    
    // Use custom x-axis label so it will display product A, B, C... instead of 1, 2, 3, 4
    NSMutableArray *labels = [[NSMutableArray alloc] initWithCapacity:[_country count]];
    int idx = 0;
    for (NSString *product in _country)
    {
        CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:product textStyle:x.labelTextStyle];
        label.tickLocation = CPTDecimalFromInt(idx);
        label.offset = 5.0f;
        [labels addObject:label];
        idx++;
    }
    x.axisLabels = [NSSet setWithArray:labels];
    
    // Setting up y-axis
	CPTXYAxis *y = axisSet.yAxis;
    y.majorIntervalLength = CPTDecimalFromInt(10);
    y.minorTicksPerInterval = 0;
    y.minorGridLineStyle = nil;
    y.title = @"Rolling CEI (%)";
    y.labelExclusionRanges = [NSArray arrayWithObjects:[CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(0) length:CPTDecimalFromInt(0)], nil];
    NSNumberFormatter *percentFormatter = [[NSNumberFormatter alloc] init];
    [percentFormatter setNumberStyle:NSNumberFormatterNoStyle];
    y.labelFormatter = percentFormatter;

    
    CPTMutableLineStyle *borderLineStyle = [CPTMutableLineStyle lineStyle];
	borderLineStyle.lineWidth = 2.f;
    borderLineStyle.lineColor = [CPTColor colorWithComponentRed:0.22f green:0.55f blue:0.71f alpha:1.0f];
    
    //========================================================================
    currentPlot = [[CPTBarPlot alloc] init];
    CPTColor *currentColor  = [CPTColor colorWithComponentRed:0.078 green:0.529 blue:0.0 alpha:1.0]; //RGB: 20-135-0  (green)
    CPTColor *currentEndColor  = [CPTColor colorWithComponentRed:0.216 green:0.671 blue:0.004 alpha:1.0]; //RGB: 55-171-1  (green)
    CPTGradient *currentGradient = [CPTGradient gradientWithBeginningColor:currentColor endingColor:currentEndColor];
    currentGradient.angle = -90.0;
    CPTFill *currentGradientFill = [CPTFill fillWithGradient:currentGradient];
    currentPlot.fill = currentGradientFill;
   //currentPlot.fill = [CPTFill fillWithColor:[CPTColor colorWithComponentRed:1.0 green:0.20 blue:0.0 alpha:1.0]];
    currentPlot.lineStyle = borderLineStyle;
    currentPlot.barWidth = CPTDecimalFromString(@"0.3");
    currentPlot.baseValue = CPTDecimalFromString(@"0");
    currentPlot.barBasesVary = NO;
    currentPlot.dataSource = self;
    //currentPlot.barCornerRadius = 2.0f;
    currentPlot.identifier = @"current CEI";
    currentPlot.barOffset  = CPTDecimalFromFloat(-0.27f);
    currentPlot.delegate = self;
    
    //========================================================================
    priorPlot = [[CPTBarPlot alloc] init];
    CPTColor *priorColor = [CPTColor colorWithComponentRed:0.051 green:0.388 blue:0.894 alpha:1.0];
    //RGB: 130-99-228  (blue)
    CPTColor *priorEndColor = [CPTColor colorWithComponentRed:0.129 green:0.545 blue:0.894 alpha:1.0];//RGB: 33-139-228  (blue)
    CPTGradient *priorGradient = [CPTGradient gradientWithBeginningColor:priorColor endingColor:priorEndColor];
    priorGradient.angle = -90.0;
    CPTFill *priorGradientFill = [CPTFill fillWithGradient:priorGradient];
    priorPlot.fill = priorGradientFill;
    //priorPlot.fill = [CPTFill fillWithColor:[CPTColor redColor]];
    //priorPlot.fill = [CPTFill fillWithColor:[CPTColor colorWithComponentRed:0.0 green:1.0 blue:0.0 alpha:1.0]];
    priorPlot.lineStyle = borderLineStyle;
    priorPlot.barWidth = CPTDecimalFromString(@"0.3");
    priorPlot.barBasesVary = NO;
    priorPlot.baseValue = CPTDecimalFromString(@"0");
    priorPlot.dataSource = self;
    //priorPlot.barCornerRadius = 2.0f;
    priorPlot.identifier = @"prior year CEI";
    priorPlot.barOffset  = CPTDecimalFromFloat(0.01f);
    priorPlot.delegate = self;
    
    //========================================================================
    allPlot = [[CPTBarPlot alloc] init];
    
    CPTColor *allColor = [CPTColor colorWithComponentRed:0.882 green:0.251 blue:0.141 alpha:1.0];   //RGB: 225-64-36  (orange)
    CPTColor *allEndColor = [CPTColor colorWithComponentRed:0.922 green:0.361 blue:0.125 alpha:1.0]; //RGB: 235-92-32  (orange)
    CPTGradient *allGradient = [CPTGradient gradientWithBeginningColor:allColor endingColor:allEndColor];
    allGradient.angle = -90.0;
    CPTFill *allGradientFill = [CPTFill fillWithGradient:allGradient];
    allPlot.fill = allGradientFill;

    //allPlot.fill = [CPTFill fillWithColor:[CPTColor colorWithComponentRed:0.0 green:0.3 blue:1.0 alpha:0.9]];
    allPlot.lineStyle = borderLineStyle;
    allPlot.barWidth = CPTDecimalFromString(@"0.3");
    allPlot.barBasesVary = NO;
    allPlot.baseValue = CPTDecimalFromString(@"0");
    allPlot.dataSource = self;
    //allPlot.barCornerRadius = 2.0f;
    allPlot.identifier = @"all collectors CEI";
    allPlot.barOffset  = CPTDecimalFromFloat(0.31f);
    allPlot.delegate = self;

    

    [graph addPlot:currentPlot toPlotSpace:plotSpace];
    [graph addPlot:priorPlot toPlotSpace:plotSpace];
    [graph addPlot:allPlot toPlotSpace:plotSpace];
    
    
    //legend for the plots
    currentPlot.title = @"CEI";
    priorPlot.title = @"Prior Year";
    allPlot.title = @"Average";
    CPTLegend *lineLegend = [CPTLegend legendWithPlots:[NSArray arrayWithObjects:currentPlot, priorPlot, allPlot, nil]]; 
    lineLegend.numberOfColumns = 3;
    graph.legend= lineLegend;
    graph.legend.fill = [CPTFill fillWithColor:[CPTColor clearColor]];
    graph.legend.cornerRadius = 5.0;
    graph.legend.swatchSize = CGSizeMake(10.0, 30.0);
    //graph.legend.swatchCornerRadius = 5.0f;
    graph.legend.swatchSize = CGSizeZero;
    graph.legendAnchor = CPTRectAnchorTop;  //CPTRectAnchorRight
    graph.legendDisplacement = CGPointMake(10.0, -80.0);  //position of the legend
    
    CPTMutableTextStyle *legendTextStyle = [[CPTMutableTextStyle alloc] init];
	legendTextStyle.color = [CPTColor darkGrayColor];
	legendTextStyle.fontSize = 11.0;
    legendTextStyle.fontName = @"Helvetica-Bold";
    graph.legend.textStyle = legendTextStyle;
    

    
    
}



#pragma mark - CPTPlotDataSource Delegates
- (NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
    
    return [_country count];
}

- (NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
    if (index == 0)
        return nil;
    
    NSNumber *num = nil;
    
    
    if (fieldEnum == CPTBarPlotFieldBarLocation)
    {
        num = [NSNumber numberWithInt:index];
    }
    else if (fieldEnum == CPTBarPlotFieldBarTip)
    {
        if (plot == currentPlot){
            CEIData *data = [[CEIData alloc] init];
            data = [_countryCEI objectForKey:[_country objectAtIndex:index]];
            num = data.ceiPercent;
            //NSLog(@"bar index=%i, data=%f",index,[data.ceiPercent floatValue]);
        } else if (plot == priorPlot){
            CEIData *data = [[CEIData alloc] init];
            data = [_countryCEI objectForKey:[_country objectAtIndex:index]];
            num = data.priorYearPercent;
            //NSLog(@"bar index=%i, data=%f",index,[num floatValue]);                      
        } else if (plot == allPlot){
            CEIData *data = [[CEIData alloc] init];
            data = [_allCEI objectForKey:[_country objectAtIndex:index]];
            num = data.ceiPercent;
            //NSLog(@"bar index=%i, data=%f",index,[num floatValue]);      
        }
    }
    /*else if (fieldEnum == CPTBarPlotFieldBarBase){
        if (plot == currentPlot){
            num = [NSNumber numberWithInt:0];
        }/ else if (plot == midBarPlot){
            Balance *bal = [[Balance alloc] init];
            bal = [_countryBalances objectAtIndex:index];
            num = bal.aboveNinetyDaysAmount;
        } else if (plot == highBarPlot){
            Balance *bal = [[Balance alloc] init];
            bal = [_countryBalances objectAtIndex:index];
            int n2 = [bal.aboveNinetyDaysAmount intValue] + [bal.belowNinetyDaysAmount intValue];
            num = [NSNumber numberWithInt:n2];             
        }
    
    }*/
    
    
    
    //NSLog(@"index =%d, country balance num=%@,fieldEnum=%d", index, num, fieldEnum);
    return num;
    
}    


@end

